from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from . import crud, schema
from educate_ai.database import get_db

# 创建路由实例
router = APIRouter(
    prefix="/users",  # 接口统一前缀
    tags=["users"],   # 接口文档分类标签
    responses={404: {"description": "Not Found"}},
)


# 1. 查询所有用户
@router.get("/", response_model=List[schema.UserInfo],summary="查询所有用户信息")
def read_all_users(
    db: Session = Depends(get_db),
    skip: int = 0,  # 分页参数：跳过前N条
    limit: int = 100  # 分页参数：最多返回N条
):
    users = crud.get_all_users(db)[skip:skip+limit]
    return users


# 2. 按ID查询用户
@router.get("/{user_id}", response_model=schema.UserInfo,summary="使用id查询指定用户信息")
def read_user(
    user_id: int,
    db: Session = Depends(get_db)
):
    db_user = crud.get_id_user(db, user_id=user_id)
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"User with id {user_id} not found"
        )
    return db_user


# 3. 按条件筛选用户
@router.get("/filter/", response_model=List[schema.UserInfo],summary='多条件查询')
def filter_users(
    user_id: int = None,
    username: str = None,
    real_name: str = None,
    db: Session = Depends(get_db)
):
    users = crud.get_by_filters(db, user_id, username, real_name)
    return users


# 4. 创建新用户
@router.post("/", response_model=schema.UserInfo, status_code=status.HTTP_201_CREATED,summary='添加用户')
def create_user(
    user: schema.CreateUser,
    db: Session = Depends(get_db)
):
    # 检查用户名是否已存在
    existing_users = crud.get_name_user(db, username=user.username)
    if existing_users:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Username '{user.username}' already exists"
        )
    return crud.add_user(db, user_schema=user)


# 5. 更新用户信息
@router.put("/{user_id}", response_model=schema.UserInfo,summary='修改用户')
def update_user(
    user_id: int,
    user_update: schema.UpdateUser,
    db: Session = Depends(get_db)
):
    # 检查用户是否存在
    db_user = crud.get_id_user(db, user_id=user_id)
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"User with id {user_id} not found"
        )
    # 若更新用户名，检查新用户名是否已存在
    if user_update.username and user_update.username != db_user.username:
        existing_users = crud.get_name_user(db, username=user_update.username)
        if existing_users:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Username '{user_update.username}' already exists"
            )
    return crud.mod_user(db, user_id=user_id, mod_schema=user_update)


# 6. 删除用户
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT,summary='删除用户')
def delete_user(
    user_id: int,
    db: Session = Depends(get_db)
):
    db_user = crud.get_id_user(db, user_id=user_id)
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"User with id {user_id} not found"
        )
    crud.delete_user(db, user_id=user_id)
    return  # 204状态码不需要返回内容